package com.jiangyg.mall.member.controller;

import com.jiangyg.mall.core.enums.Enable;
import com.jiangyg.mall.core.support.restful.Pagination;
import com.jiangyg.mall.core.support.restful.Result;
import com.jiangyg.mall.member.dto.MemberDTO;
import com.jiangyg.mall.member.service.MemberService;
import com.jiangyg.mall.member.vo.MemberVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 类描述：会员控制器
 *
 * @author jiangyg
 * @version email@jiangyg.com
 * @date 2021-10-30 07:33:09
 */
@RestController
@RequestMapping("/member/member")
public class MemberController {

    /**
     * 会员接口
     */
    private final MemberService memberService;

    @Autowired
    public MemberController(MemberService memberService) {
        this.memberService = memberService;
    }

    /**
     * 功能描述：会员分页查询
     *
     * @param request    请求
     * @param pagination 分页参数
     * @return 返回分页会员
     */
    @ResponseBody
    @PostMapping("/select")
    public Result<Pagination<MemberVO>> select(HttpServletRequest request, @RequestBody Pagination<MemberVO> pagination) throws Exception {
        return Result.ok(memberService.selectPagination(pagination));
    }

    /**
     * 功能描述：注册会员
     *
     * @param request 请求
     * @param dto     会员
     * @return 结果
     */
    @ResponseBody
    @PostMapping("/register")
    public Result<Boolean> register(HttpServletRequest request, @RequestBody @Validated MemberDTO dto) throws Exception {
        // TODO 待模拟真实场景
        return Result.saveOrUpdate(memberService.register(dto));
    }

    /**
     * 功能描述：根据ID获取会员
     *
     * @param request  请求
     * @param memberId 会员ID
     * @return 结果
     */
    @ResponseBody
    @PostMapping("/info")
    public Result<MemberVO> info(HttpServletRequest request, @RequestParam(name = "memberId") Long memberId) throws Exception {
        return Result.ok(memberService.selectById(memberId));
    }

    /**
     * 功能描述：删除会员
     *
     * @param request   请求
     * @param memberIds 批量删除的会员ID
     * @return 结果
     */
    @ResponseBody
    @PostMapping("/delete")
    public Result<Object> delete(HttpServletRequest request, @RequestParam(name = "memberIds") List<Long> memberIds) {
        return Result.delete(memberService.delete(memberIds));
    }

    /**
     * 功能描述：查询手机号是否已注册
     *
     * @param request 请求
     * @param mobile  手机号
     * @return 结果
     */
    @ResponseBody
    @PostMapping("/mobile-registered")
    public Result<String> mobileRegistered(HttpServletRequest request, @RequestParam(name = "mobile") String mobile) {
        final boolean registered = memberService.mobileRegistered(mobile);
        return Result.ok(registered ? Enable.Y.scode : Enable.N.scode);
    }

}
